<template>
  <div class="general-select">
    <el-row :gutter="20">
      <el-col :span="6" class="project-list">
        <el-card class="project-card" shadow="hover">
          <el-table
              :data="tableData"
              style="width: 100%"
              stripe
              highlight-current-row
              @row-click="getDetails">
            <el-table-column
                prop="projectName"
                label="项目"
                class-name="project-column">
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="16" v-if="projectDetails" class="project-details">
        <el-card class="gantt-card">
          <div slot="header">
            <span>项目进度甘特图</span>
          </div>
          <div class="gantt-container" ref="ganttChart"></div>
        </el-card>
        <el-card>
          <h1>项目信息</h1>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="info-card">
                <p><strong>项目ID:</strong> {{ projectDetails.projectId }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>项目名称:</strong> {{ projectDetails.projectName }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>项目进度:</strong> {{ projectDetails.taskProgress }}%</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>负责人ID:</strong> {{ projectDetails.responsibleId }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>重要程度:</strong> {{ projectDetails.importantLevel }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>项目状态:</strong> {{ projectDetails.projectStatus }}</p>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="info-card">
                <p><strong>开始时间:</strong> {{ formatDate(projectDetails.startDate) }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>结束时间:</strong> {{ formatDate(projectDetails.endDate) }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>预算:</strong> {{ projectDetails.budget }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>合同额:</strong> {{ projectDetails.contractAmount }}</p>
              </el-card>
              <el-card class="info-card">
                <p><strong>项目类别:</strong> {{ projectDetails.projectType }}</p>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
        <div class="project-buttons">
          <el-row :gutter="20" align="middle" justify="center">
            <el-col :span="12" style="text-align: center;">
              <el-button type="primary" @click="updateProjectStatus(1)">通过审查</el-button>
            </el-col>
            <el-col :span="12" style="text-align: center;">
              <el-button type="danger" @click="updateProjectStatus(0)">不通过审查</el-button>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import http from "@/api/http";
import * as echarts from 'echarts';

export default {
  name: 'CheckPage',
  data() {
    return {
      id: 0,
      tableData: [],
      projectDetails: null,
      ganttChart: null,
      projectTasks: []
    }
  },
  methods: {
    async getDetails(row) {
      console.log("选中的项目:", row);
      this.id = row.projectId;
      
      try {
        await this.fetchProjectDetails(this.id);
        await this.fetchProjectTasks(this.id);
        
        if (this.projectTasks && this.projectTasks.length > 0) {
          this.$nextTick(() => {
            this.initGanttChart();
          });
        }
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    },
    getinfo() {
      http.get("/api/audit/pending")
          .then(res => {
            this.tableData = res;
            console.log(res);
            // 在获取到数据后，如果存在数据则自动选择第一个项目
            if (res && res.length > 0) {
              this.getDetails(res[0]);
            }
          })
          .catch(error => {
            console.error("Error fetching projects:", error);
          });
    },
    fetchProjectDetails(projectId) {
      http.get(`/api/general/project/${projectId}`)
          .then(res => {
            this.projectDetails = res;
            console.log("Project details:", res);
          })
          .catch(error => {
            console.error(`Error fetching project ${projectId} details:`, error);
          });
    },
    updateProjectStatus(isApproved) {
      const projectId = this.projectDetails.projectId;
      console.log(projectId)
      http.post(`/api/audit/updateStatus`, null, {
        params: {
          projectId: projectId,
          isApproved: isApproved
        }
      })
          .then(res => {
            this.$message.success(res);
            console.log(res);
            this.projectDetails = null; // 清空 projectDetails 使 el-card 不显示
            this.getinfo(); // 更新列表
          })
          .catch(error => {
            console.error(`Error updating project status for project ${projectId}:`, error);
            this.$message.error("Failed to update project status");
          });
    },
    async fetchProjectTasks(projectId) {
      try {
        const response = await http.get(`/api/tasks/project/${projectId}/tasks`);
        if (response) {
          this.projectTasks = response;
        } else {
          this.projectTasks = [];
        }
      } catch (error) {
        console.error(`Error fetching tasks for project ${projectId}:`, error);
        this.$message.error('获取任务数据失败');
        this.projectTasks = [];
      }
    },

    initGanttChart() {
      if (this.ganttChart) {
        this.ganttChart.dispose();
      }

      const chartDom = this.$refs.ganttChart;
      if (!chartDom) {
        console.error('Cannot find gantt chart container');
        return;
      }

      this.ganttChart = echarts.init(chartDom);

      if (!this.projectTasks || this.projectTasks.length === 0) {
        console.warn('没有任务数据');
        return;
      }

      // 使用项目的开始和结束时间
      const projectStartDate = this.projectDetails.startDate ? new Date(this.projectDetails.startDate) : new Date();
      const projectEndDate = this.projectDetails.endDate ? new Date(this.projectDetails.endDate) : new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);

      // 首先创建任务数组并按开始时间排序
      const tasks = this.projectTasks
          .map(task => {
            const taskStartTime = task.startDate ? new Date(task.startDate) : projectStartDate;
            const taskEndTime = task.endDate ? new Date(task.endDate) : projectEndDate;

            return {
              name: task.taskName,
              status: (task.taskStatus === '待审核' || task.taskStatus === '已审核') ? 2 : 0,
              percentage: task.taskPercentage || 0,
              startTime: taskStartTime,
              endTime: taskEndTime
            };
          })
          .sort((a, b) => a.startTime - b.startTime); // 按开始时间升序排序

      console.log('处理后的排序任务数据:', tasks);

      // 抽取公共逻辑为辅助函数
      const getTaskDisplay = (task) => ({
        color: task.status === 2 ? '#67C23A' : '#909399',  // 已完成-绿色，未完成-灰色
        text: task.status === 2 ? '已完成' : '未完成',
        progress: task.status === 2 ? 100 : (task.percentage || 0)
      });

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const task = tasks[params[0].dataIndex];
            const display = getTaskDisplay(task);

            return `
              <div style="padding: 3px;">
                <div>${task.name}</div>
                <div>开始时间: ${task.startTime.toLocaleDateString()}</div>
                <div>结束时间: ${task.endTime.toLocaleDateString()}</div>
                <div>权重: ${task.percentage}%</div>
                <div>状态: <span style="color:${display.color}">${display.text}</span></div>
              </div>
            `;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'time',
          axisLabel: {
            formatter: '{yyyy}-{MM}-{dd}'
          },
          splitLine: {
            show: true
          },
          min: projectStartDate.getTime(),
          max: projectEndDate.getTime(),
          interval: 24 * 3600 * 1000,
          axisPointer: {
            snap: true
          }
        },
        yAxis: {
          type: 'category',
          data: tasks.map(task => task.name) // 使用排序后的任务名称数组
        },
        series: [
          {
            // 背景进度条
            name: '任务进度',
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: params => {
                const task = tasks[params.dataIndex];
                return task.status === 2 ? '#67C23A' : '#909399';
              }
            },
            emphasis: {
              disabled: true
            },
            barWidth: 20,
            data: tasks.map(task => ({
              value: [
                task.endTime.getTime(),
                task.name,
                task.endTime.getTime()
              ],
            }))
          },
          {
            // 白色覆盖层
            name: '覆盖层',
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: '#f5f5f5'
            },
            emphasis: {
              disabled: true
            },
            barWidth: 20,
            data: tasks.map(task => ({
              value: [
                task.startTime.getTime(),
                task.name,
                task.startTime.getTime()
              ]
            })),
            tooltip: {
              show: false
            }
          }
        ]
      };

      console.log('图表数据:', {
        taskNames: option.yAxis.data,
        progressData: option.series[0].data,
        tasks: tasks
      });

      this.ganttChart.setOption(option);
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString();
    }
  },
  created() {
    this.getinfo();
  },
  mounted() {
    window.addEventListener('resize', () => {
      if (this.ganttChart) {
        this.ganttChart.resize();
      }
    });
  },
  beforeDestroy() {
    if (this.ganttChart) {
      this.ganttChart.dispose();
    }
    window.removeEventListener('resize', () => {
      if (this.ganttChart) {
        this.ganttChart.resize();
      }
    });
  }
}
</script>

<style scoped>
.general-select {
  padding: 20px;
  background-color: #f0f2f5;
}

.project-list {
  max-height: 800px;
  overflow-y: auto;
}

.project-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.project-column .cell {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.project-list::-webkit-scrollbar {
  width: 6px;
}

.project-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.project-list::-webkit-scrollbar-track {
  background: #f8f9fa;
}

.el-table__row:hover {
  cursor: pointer;
}

.project-details {
  margin-left: 20px;
  padding: 20px;
}

.project-details h1 {
  font-size: 24px;
  margin-bottom: 20px;
}

.project-details p {
  font-size: 16px;
  margin: 5px 0;
}

.project-buttons {
  margin-top: 20px;
}

.gantt-card {
  margin-bottom: 20px;
}

.gantt-container {
  width: 100%;
  height: 300px;
  margin: 10px 0;
  background-color: #f5f5f5;
}
</style>

<style>
body {
  background-color: #f0f2f5;
}

.el-table th {
  background-color: #f5f7fa !important;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}
</style>